﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WeiboPlus.Common;
using Coding4Fun.Phone.Controls;
using WeiboPlus.Models;
using WeiboPlus.Shell.ViewModel;
using System.Diagnostics;

namespace WeiboPlus.Shell.Views
{
    public partial class SearchView : PhoneApplicationPage
    {
        SearchViewModel _viewmodel;
        private bool hasInit = false;
        //ScrollViewer svHome;

        public SearchView()
        {
            InitializeComponent();

            _viewmodel = new SearchViewModel();

            this.DataContext = _viewmodel;

            _viewmodel.PropertyChanged += _viewmodel_PropertyChanged;

            Loaded += (s, e) =>
            {
                if (hasInit)
                    return;
                hasInit = true;

                if (NavigationContext.QueryString.ContainsKey("key"))
                {
                    var key = NavigationContext.QueryString["key"];

                    if (!string.IsNullOrWhiteSpace(key))
                    {
                        if (NavigationContext.QueryString.ContainsKey("mode"))
                        {
                            var mode = NavigationContext.QueryString["mode"];
                            if (mode == "user")
                            {
                                _viewmodel.PivotSelectedIndex = 1;
                            }
                        }
                        _viewmodel.SearchKeyword = key;
                        _viewmodel.Search();
                    }
                    else
                    {
                        try
                        {
                            var k = string.Empty;
                            var query = NavigationService.CurrentSource.OriginalString.Split('?')[1];
                            foreach (var qs in query.Split('&'))
                            {
                                if (qs.StartsWith("key="))
                                {
                                    k = qs.Split('=')[1];
                                }
                            }


                            if (!string.IsNullOrEmpty(k))
                            {
                                _viewmodel.SearchKeyword = k;
                                _viewmodel.Search();
                            }
                        }
                        catch
                        {
                            tbSearchWord.Focus();
                            return;
                        }
                    }
                }
                else
                {
                    tbSearchWord.Focus();
                }
            };
        }

        void _viewmodel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
#if DEBUG
            Debug.WriteLine("Property changed:" + e.PropertyName);
#endif
            switch (e.PropertyName)
            {

                case "Loading":
                    if (_viewmodel.Loading)
                    {
                        progressIndicator.IsIndeterminate = true;
                        HideMenu();
                    }
                    else
                    {
                        progressIndicator.IsIndeterminate = false;
                        PopulateMenu();
                    }
                    break;
                case "PivotSelectedIndex":
                    //if (PhoneApplicationService.Current.State.ContainsKey("PivotSelectedIndex"))
                    //    PhoneApplicationService.Current.State["PivotSelectedIndex"] = _mainViewModel.PivotSelectedIndex;
                    //else
                    //    PhoneApplicationService.Current.State.Add("PivotSelectedIndex", _mainViewModel.PivotSelectedIndex);
                    SetAppIconButton(_viewmodel.PivotSelectedIndex);
                    break;

                default:
                    break;
            }
        }

        private void PopulateMenu()
        {
            if (!this.ApplicationBar.IsVisible
                && (this.ApplicationBar.Buttons.Count > 0 || this.ApplicationBar.MenuItems.Count > 0))
                this.ApplicationBar.IsVisible = true;
        }

        private void HideMenu()
        {
            if (this.ApplicationBar == null)
                return;
            if (this.ApplicationBar.IsVisible)
                this.ApplicationBar.IsVisible = false;
        }

        private void SetAppIconButton(int pIndex)
        {
            ApplicationBar.Buttons.Clear();

            switch (pIndex)
            {
                case 0:
                    //var performSearch = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/appbar.search.rest.png", UriKind.Relative)) { Text = AppResx.SearchTopicText };
                    //performSearch.Click += new EventHandler(performSearch_Click);
                    //var clearSearchText = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/delete.png", UriKind.Relative)) { Text = AppResx.EmptyText };
                    //clearSearchText.Click += new EventHandler(clearSearchText_Click);

                    //ApplicationBar.Buttons.Add(performSearch);
                    //ApplicationBar.Buttons.Add(clearSearchText);

                    break;
                case 5:

                    break;
                default:
                    break;
            }

            //throw new NotImplementedException();
        }

        private void ContentGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var status = (e.AddedItems[0] as SNSStatusViewModel).Item;
                //if (status.Provider == SNSProviderType.RenRen)
                //{
                //    var toast = new ToastPrompt
                //    {
                //        Message = string.Format(AppResx.NoSupportedBy, status.Provider),
                //    };
                //    toast.Show();
                //    return;
                //}

                var key = status.Id.ToString();

                if (PhoneApplicationService.Current.State.ContainsKey(key))
                {
                    PhoneApplicationService.Current.State.Remove(key);
                }

                PhoneApplicationService.Current.State.Add(key, status);
                NavigationService.Navigate(new Uri("/Views/StatusDetailView.xaml?" + key, UriKind.RelativeOrAbsolute));
            }
            var list = sender as ListBox;
            if (list != null)
            {
                list.SelectionChanged -= ContentGrid_SelectionChanged;
                list.SelectedIndex = -1;
                list.SelectionChanged += ContentGrid_SelectionChanged;
            }
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            _viewmodel.Search();
        }

        private void OnUserSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var user = e.AddedItems[0] as SNSUser;
                var key = user.AccountName + "=" + user.AccountID;

                if (PhoneApplicationService.Current.State.ContainsKey(key))
                {
                    PhoneApplicationService.Current.State.Remove(key);
                }

                PhoneApplicationService.Current.State.Add(key, user);
                NavigationService.Navigate(new Uri("/Views/UserHomeView.xaml?" + key, UriKind.Relative));
            }
        }
    }
}